package com.app.diary.ui;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.app.diary.BuildConfig;
import com.app.diary.Mapp;
import com.app.diary.R;
import com.app.diary.bean.Diary;
import com.app.diary.data.impl.WeatherApiService;
import com.app.diary.data.model.WeatherResponse;
import com.app.diary.utils.ToastUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import okhttp3.HttpUrl;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class DiaryEditActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final String EXTRA_DIARY_ID = "extra_diary_id";
    private static final String API_KEY = "b7c81e1dabd749eda4003517e1554a31"; // 确保这是你的有效 API Key
    private static final String LOCATION_ID_GUANGZHOU = "101010100"; // 广州的 Location ID

    private long diaryId;
    private DatePickerDialog datePickerDialog;

    private Toolbar toolbar;
    private TextView dateTextView;
    private TextView weatherTextView;
    private EditText titleEditText;
    private EditText contentEditText;

    private WeatherApiService weatherApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_edit);

        initData();
        initView();
        setView();

        // 初始化 Retrofit 和 WeatherApiService
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://devapi.qweather.com/v7/") // 确保 baseUrl 以斜杠 / 结尾
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        weatherApiService = retrofit.create(WeatherApiService.class);
    }

    private void initData() {
        diaryId = getIntent().getLongExtra(EXTRA_DIARY_ID, 0);
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        dateTextView = findViewById(R.id.date_textView);
        weatherTextView = findViewById(R.id.weather_textView);
        titleEditText = findViewById(R.id.title_editText);
        contentEditText = findViewById(R.id.content_editText);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        dateTextView.setOnClickListener(v -> showDatePickerDialog());
        if (weatherTextView != null) { // 防止 NullPointerException
            weatherTextView.setOnClickListener(v -> getLocationAndWeather());
        }
    }

    private void setView() {
        if (diaryId > 0) { // 修改日记
            Diary diary = Mapp.getInstance().getDiaryDataSource().selectOne(diaryId);
            if (diary == null) {
                ToastUtils.showShort("未找到该日记");
                finish();
                return;
            }
            toolbar.setTitle("修改日记");
            dateTextView.setText(formatDate(diary.getDate()));
            weatherTextView.setText(diary.getWeather());
            titleEditText.setText(diary.getTitle());
            contentEditText.setText(diary.getContent());
        } else { // 创建日记
            toolbar.setTitle("创建日记");
            dateTextView.setText(formatDate(new Date()));
        }
    }

    private void getLocationAndWeather() {
        queryGuangzhouWeather();
    }

    private void queryGuangzhouWeather() {
        Call<WeatherResponse> call = weatherApiService.getWeather(LOCATION_ID_GUANGZHOU, API_KEY); // 使用常量

        // 获取完整的请求 URL
        HttpUrl url = call.request().url();
        Log.d("WeatherApi", "Full Request URL: " + url.toString());

        call.enqueue(new Callback<WeatherResponse>() {
            @Override
            public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    WeatherResponse weatherResponse = response.body();
                    if ("200".equals(weatherResponse.getCode())) { // 检查是否成功
                        String weatherInfo = "天气: " + weatherResponse.getNow().getText() + ", 温度: " + weatherResponse.getNow().getTemp() + "°C";
                        runOnUiThread(() -> weatherTextView.setText(weatherInfo));
                    } else {
                        String errorCode = weatherResponse.getCode();
                        String errorMessage = weatherResponse.getMessage();
                        Log.e("WeatherApi", "API returned error code: " + errorCode + ", message: " + errorMessage);
                        runOnUiThread(() -> ToastUtils.showShort("获取天气信息失败：API返回错误"));
                    }
                } else {
                    Log.e("WeatherApi", "Failed to get weather information: " + response.code() + " " + response.message());
                    runOnUiThread(() -> ToastUtils.showShort("无法获取天气信息"));
                }
            }

            @Override
            public void onFailure(Call<WeatherResponse> call, Throwable t) {
                Log.e("WeatherApi", "Network request failed: " + t.getMessage(), t);
                runOnUiThread(() -> ToastUtils.showShort("网络请求失败，请检查网络连接"));
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // startLocationService(); （已注释）
            } else {
                ToastUtils.showShort("位置权限被拒绝，无法获取当前天气信息。");
            }
        }
    }

    private void showDatePickerDialog() {
        if (datePickerDialog == null) {
            Calendar calendar = Calendar.getInstance();
            try {
                String dateStr = dateTextView.getText().toString().trim();
                Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(dateStr);
                calendar.setTime(date);
            } catch (ParseException e) {
                calendar.setTime(new Date()); // 使用当前日期作为默认值
            }
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            datePickerDialog = new DatePickerDialog(DiaryEditActivity.this, (view, year1, monthOfYear, dayOfMonth) -> {
                Date date = getDate(year1, monthOfYear, dayOfMonth);
                String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
                dateTextView.setText(dateStr);
            }, year, month, day);
        }
        if (!datePickerDialog.isShowing()) {
            datePickerDialog.show();
        }
    }

    private Date getDate(int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        return calendar.getTime();
    }

    private void saveDiary() {
        String date = dateTextView.getText().toString().trim();
        if (date.isEmpty()) {
            ToastUtils.showShort("未选择日期");
            return;
        }
        String weather = weatherTextView.getText().toString().trim();
        if (weather.isEmpty()) {
            ToastUtils.showShort("未选择天气");
            return;
        }
        String title = titleEditText.getText().toString().trim();
        if (title.isEmpty()) {
            ToastUtils.showShort("未输入标题");
            return;
        }
        String content = contentEditText.getText().toString().trim();
        if (content.isEmpty()) {
            ToastUtils.showShort("未输入内容");
            return;
        }
        Diary diary = new Diary();
        try {
            diary.setDate(new SimpleDateFormat("yyyy年MM月dd日").parse(date));
        } catch (ParseException e) {
            ToastUtils.showShort("保存失败，时间转换错误");
            return;
        }
        diary.setWeather(weather);
        diary.setTitle(title);
        diary.setContent(content);
        if (diaryId > 0) {
            Mapp.getInstance().getDiaryDataSource().updateDiary(diaryId, diary);
        } else {
            Mapp.getInstance().getDiaryDataSource().insertDiary(diary);
        }
        ToastUtils.showShort("保存成功");
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_diary_create, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:
                saveDiary();
                break;
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (datePickerDialog != null && datePickerDialog.isShowing()) {
            datePickerDialog.dismiss();
        }
    }

    public static Intent buildIntent(@NonNull Context context, long diaryId) {
        Intent intent = new Intent(context, DiaryEditActivity.class);
        intent.putExtra(EXTRA_DIARY_ID, diaryId);
        return intent;
    }

    private String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return sdf.format(date);
    }
}



